<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购入库单编号" prop="purchaseInNo">
        <el-input
          v-model="queryParams.purchaseInNo"
          placeholder="请输入采购入库单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供货商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供货商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:in:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:in:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:in:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:in:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="采购入库单编号" align="center" prop="purchaseInNo" min-width="180" show-overflow-tooltip />
      <el-table-column label="存货编码" align="center" prop="inventoryCode" min-width="160" show-overflow-tooltip />
      <el-table-column label="存货名称" align="center" prop="inventoryName" min-width="200" show-overflow-tooltip />
      <el-table-column label="供货商编码" align="center" prop="supplierCode" min-width="160" />
      <el-table-column label="供货商名称" align="center" prop="supplierName" min-width="200" show-overflow-tooltip />
      <el-table-column label="仓库编码" align="center" prop="warehouseCode" min-width="140" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" min-width="180" show-overflow-tooltip />
      <el-table-column label="入库日期" align="center" prop="putawayDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.putawayDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总数量" align="center" prop="totalQuantity" min-width="140" />
      <el-table-column label="入库操作人" align="center" prop="putawayOperator" min-width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:in:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:in:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="扫码">
              <div style="display:flex;gap:8px;align-items:center;">
                <el-input v-model="scanInput" placeholder="请输入或扫描箱码" clearable @keyup.enter.native="handleScanEnter" />
                <el-button type="primary" size="mini" @click="handleScanEnter">添加</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库人">
              <el-input v-model="form.putawayOperator" placeholder="请输入入库操作人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库仓库">
              <el-select v-model="form.warehouseCode" placeholder="请选择仓库" filterable clearable @change="onWarehouseChange">
                <el-option
                  v-for="w in warehouseOptions"
                  :key="w.warehouseCode"
                  :label="`${w.warehouseCode} - ${w.warehouseName}`"
                  :value="w.warehouseCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库数量">
              <el-input v-model="form.totalQuantity" placeholder="自动汇总装箱数量" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批量带入">
              <el-switch v-model="batchImport" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">箱码清单</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-show="!isCreateMode"
              :disabled="isCreateMode"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddBizPurchaseInBarcode"
            >添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBizPurchaseInBarcode">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="bizPurchaseInBarcodeList" :row-class-name="rowBizPurchaseInBarcodeIndex" @selection-change="handleBizPurchaseInBarcodeSelectionChange" ref="bizPurchaseInBarcode">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column label="箱码" prop="barcode" width="180">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.barcode }}</span>
              <el-input v-else v-model="scope.row.barcode" placeholder="请输入箱码" />
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="160">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.batchNo }}</span>
              <el-input v-else v-model="scope.row.batchNo" placeholder="请输入批次号" />
            </template>
          </el-table-column>
          <el-table-column label="存货编码" prop="inventoryCode" width="160">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.inventoryCode }}</span>
              <el-input v-else v-model="scope.row.inventoryCode" placeholder="请输入存货编码" />
            </template>
          </el-table-column>
          <el-table-column label="存货名称" prop="inventoryName" width="180">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.inventoryName }}</span>
              <el-input v-else v-model="scope.row.inventoryName" placeholder="请输入存货名称" />
            </template>
          </el-table-column>
          <el-table-column label="供应商编码" prop="supplierCode" width="160">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.supplierCode }}</span>
              <el-input v-else v-model="scope.row.supplierCode" placeholder="请输入供应商编码" />
            </template>
          </el-table-column>
          <el-table-column label="供应商名称" prop="supplierName" width="180">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.supplierName }}</span>
              <el-input v-else v-model="scope.row.supplierName" placeholder="请输入供应商名称" />
            </template>
          </el-table-column>
          <el-table-column label="装箱数量" prop="packQuantity" width="140">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.packQuantity }}</span>
              <el-input v-else v-model="scope.row.packQuantity" placeholder="请输入装箱数量" />
            </template>
          </el-table-column>
          <el-table-column label="计量单位" prop="unitCode" width="140">
            <template slot-scope="scope">
              <span v-if="isCreateMode">{{ scope.row.unitCode }}</span>
              <el-input v-else v-model="scope.row.unitCode" placeholder="请输入计量单位" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listIn, getIn, delIn, addIn, updateIn } from "@/api/system/in"
import { listWarehouse } from "@/api/system/warehouse"
import { listBarcode } from "@/api/system/barcode"
// 后端已聚合返回存货编码/名称，前端无需再按编码补全名称

export default {
  name: "In",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBizPurchaseInBarcode: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购入库单表格数据
      inList: [],
      // 采购入库箱码明细表格数据
      bizPurchaseInBarcodeList: [],
      // 扫码输入
      scanInput: "",
      // 批量带入开关
      batchImport: true,
      // 仓库下拉选项
      warehouseOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 新增弹窗模式（新增时只读显示箱码清单）
      isCreateMode: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseInNo: null,
        supplierName: null,
        warehouseName: null,
        // 默认按创建时间倒序（新创建的在上面）
        orderByColumn: 'created_time',
        isAsc: 'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseCode: [
          { required: true, message: "入库仓库不能为空", trigger: "change" }
        ],
        putawayOperator: [
          { required: true, message: "入库人不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.loadWarehouseOptions()
  },
  watch: {
    bizPurchaseInBarcodeList: {
      deep: true,
      handler(list) {
        const total = (list || []).reduce((sum, r) => {
          const v = parseFloat(r.packQuantity)
          return sum + (isNaN(v) ? 0 : v)
        }, 0)
        this.form.totalQuantity = total
        this.form.totalBoxes = (list || []).length
      }
    },
    batchImport(val) {
      this.form.putawayType = val ? 'BATCH' : 'SINGLE'
    }
  },
  methods: {
    /** 查询采购入库单列表（直接使用后端聚合返回） */
    getList() {
      this.loading = true
      listIn(this.queryParams).then(response => {
        this.inList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseInId: null,
        purchaseInNo: null,
        receiptNoteId: null,
        receiptNoteNo: null,
        deliveryNoteNo: null,
        supplierCode: null,
        supplierName: null,
        warehouseCode: null,
        warehouseName: null,
        putawayDate: null,
        putawayStatus: null,
        totalBoxes: null,
        totalQuantity: null,
        putawayType: 'BATCH',
        putawayOperator: null,
        confirmedBy: null,
        confirmedTime: null,
        rollbackReason: null,
        rollbackOperator: null,
        rollbackTime: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        delFlag: null
      }
      this.bizPurchaseInBarcodeList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseInId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.loadWarehouseOptions()
      this.open = true
      this.isCreateMode = true
      this.title = "添加采购入库单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const purchaseInId = row.purchaseInId || this.ids
      getIn(purchaseInId).then(response => {
        this.form = response.data
        this.bizPurchaseInBarcodeList = response.data.bizPurchaseInBarcodeList
        this.loadWarehouseOptions()
        this.open = true
        this.isCreateMode = false
        this.title = "修改采购入库单"
      })
    },
    /** 加载仓库选项 */
    loadWarehouseOptions() {
      listWarehouse({ pageNum: 1, pageSize: 9999 }).then(res => {
        this.warehouseOptions = res.rows || []
      })
    },
    /** 仓库选择变更时同步仓库名称 */
    onWarehouseChange(code) {
      const w = (this.warehouseOptions || []).find(o => o.warehouseCode === code)
      this.form.warehouseName = w ? w.warehouseName : ''
    },
    /** 扫码添加到箱码清单（仅允许已质检 INSPECTED） */
    async handleScanEnter() {
      const value = (this.scanInput || '').trim()
      if (!value) {
        this.$modal && this.$modal.msgWarning ? this.$modal.msgWarning('请先输入或扫描箱码') : null
        return
      }

      try {
        // 1) 按箱码查询，并在前端过滤仅带入已质检的箱码
        const bcRes = await listBarcode({ barcode: value, isRejected: '0', barcodeStatus: 'INSPECTED', pageNum: 1, pageSize: 9999 })
        const allRows = (bcRes && Array.isArray(bcRes.rows)) ? bcRes.rows : []
        const inspectedRows = allRows.filter(r => r.barcodeStatus === 'INSPECTED' && String(r.isRejected) !== '1')
        if (inspectedRows.length === 0) {
          this.$modal && this.$modal.msgError ? this.$modal.msgError('仅能带入已质检且未拒收的箱码') : null
          return
        }
        const first = inspectedRows[0]

        // 2) 根据“批量带入”为“是”时，带入同批次已质检的箱码
        let toAdd = [first]
        if (this.batchImport && first.batchNo) {
          const batchRes = await listBarcode({ batchNo: first.batchNo, isRejected: '0', barcodeStatus: 'INSPECTED', pageNum: 1, pageSize: 9999 })
          const batchAllRows = (batchRes && Array.isArray(batchRes.rows)) ? batchRes.rows : []
          const batchList = batchAllRows.filter(r => r.barcodeStatus === 'INSPECTED' && String(r.isRejected) !== '1')
          toAdd = batchList.length > 0 ? batchList : [first]
        }

        // 3) 去重并映射字段到清单
        const exists = new Set((this.bizPurchaseInBarcodeList || []).map(r => r.barcode))
        const mapped = []
        toAdd.forEach(b => {
          if (!exists.has(b.barcode)) {
            mapped.push({
              barcodeId: b.barcodeId || null,
              barcode: b.barcode,
              batchNo: b.batchNo || '',
              inventoryCode: b.inventoryCode || '',
              inventoryName: b.inventoryName || '',
              supplierCode: b.supplierCode || '',
              supplierName: b.supplierName || '',
              packQuantity: b.packQuantity != null ? ('' + b.packQuantity) : '',
              unitCode: b.unitCode || ''
            })
          }
        })
        if (mapped.length === 0) {
          this.$modal && this.$modal.msgWarning ? this.$modal.msgWarning('已存在，不重复添加') : null
          this.scanInput = ''
          return
        }

        this.bizPurchaseInBarcodeList = this.bizPurchaseInBarcodeList.concat(mapped)
        this.scanInput = ''
      } catch (e) {
        console.error('handleScanEnter error', e)
        this.$modal && this.$modal.msgError ? this.$modal.msgError('查询箱码失败，请稍后重试') : null
      }
    },
    /** 在提交前尽量为手工录入的箱码补全 barcodeId，提升联动效果 */
    async resolveBarcodeIdsBeforeSubmit() {
      try {
        const needLookup = (this.bizPurchaseInBarcodeList || []).filter(x => !x.barcodeId && x.barcode)
        if (needLookup.length === 0) return
        await Promise.all(needLookup.map(async x => {
          try {
            const r = await listBarcode({ barcode: x.barcode, isRejected: '0', pageNum: 1, pageSize: 1 })
            const b = (r && Array.isArray(r.rows)) ? r.rows[0] : null
            if (b && b.barcodeId) { x.barcodeId = b.barcodeId }
            // 兜底填充常用字段，避免手工录入不全
            if (b && !x.packQuantity && b.packQuantity != null) { x.packQuantity = '' + b.packQuantity }
            if (b && !x.inventoryCode && b.inventoryCode) { x.inventoryCode = b.inventoryCode }
            if (b && !x.inventoryName && b.inventoryName) { x.inventoryName = b.inventoryName }
            if (b && !x.unitCode && b.unitCode) { x.unitCode = b.unitCode }
            if (b && !x.supplierCode && b.supplierCode) { x.supplierCode = b.supplierCode }
            if (b && !x.supplierName && b.supplierName) { x.supplierName = b.supplierName }
            if (b && !x.batchNo && b.batchNo) { x.batchNo = b.batchNo }
          } catch (e) {}
        }))
      } catch (e) {}
    },
    /** 提交按钮 */
    async submitForm() {
      // 前置校验：入库仓库、入库人、箱码清单必填/必有
      const warehouseEmpty = !this.form.warehouseCode
      const operatorEmpty = !this.form.putawayOperator || ('' + this.form.putawayOperator).trim() === ''
      const noBarcodes = !Array.isArray(this.bizPurchaseInBarcodeList) || this.bizPurchaseInBarcodeList.length === 0

      if (warehouseEmpty) {
        if (this.$modal && this.$modal.msgWarning) {
          this.$modal.msgWarning('入库仓库不能为空')
        } else if (this.$message && this.$message.warning) {
          this.$message.warning('入库仓库不能为空')
        }
        return
      }
      if (operatorEmpty) {
        if (this.$modal && this.$modal.msgWarning) {
          this.$modal.msgWarning('入库人不能为空')
        } else if (this.$message && this.$message.warning) {
          this.$message.warning('入库人不能为空')
        }
        return
      }
      if (noBarcodes) {
        if (this.$modal && this.$modal.msgWarning) {
          this.$modal.msgWarning('箱码清单为空，请先扫码带入')
        } else if (this.$message && this.$message.warning) {
          this.$message.warning('箱码清单为空，请先扫码带入')
        }
        return
      }

      await this.resolveBarcodeIdsBeforeSubmit()
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.form.bizPurchaseInBarcodeList = this.bizPurchaseInBarcodeList
          if (this.form.purchaseInId != null) {
            await updateIn(this.form)
            this.$modal.msgSuccess("修改成功")
          } else {
            await addIn(this.form)
            this.$modal.msgSuccess("新增成功")
          }
          this.open = false
          this.getList()
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseInIds = row.purchaseInId || this.ids
      this.$modal.confirm('是否确认删除采购入库单编号为"' + purchaseInIds + '"的数据项？').then(function() {
        return delIn(purchaseInIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 采购入库箱码明细序号 */
    rowBizPurchaseInBarcodeIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 采购入库箱码明细添加按钮操作 */
    handleAddBizPurchaseInBarcode() {
      const obj = {
        barcode: "",
        batchNo: "",
        inventoryCode: "",
        inventoryName: "",
        supplierCode: this.form.supplierCode || "",
        supplierName: this.form.supplierName || "",
        packQuantity: "",
        unitCode: ""
      }
      this.bizPurchaseInBarcodeList.push(obj)
    },
    /** 采购入库箱码明细删除按钮操作 */
    handleDeleteBizPurchaseInBarcode() {
      if (this.checkedBizPurchaseInBarcode.length == 0) {
        this.$modal.msgError("请先选择要删除的采购入库箱码明细数据")
      } else {
        const bizPurchaseInBarcodeList = this.bizPurchaseInBarcodeList
        const checkedBizPurchaseInBarcode = this.checkedBizPurchaseInBarcode
        this.bizPurchaseInBarcodeList = bizPurchaseInBarcodeList.filter(function(item) {
          return checkedBizPurchaseInBarcode.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleBizPurchaseInBarcodeSelectionChange(selection) {
      this.checkedBizPurchaseInBarcode = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/in/export', {
        ...this.queryParams
      }, `in_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
